//
//  DictionaryService.swift
//  GreenDeal
//
//  Created by Moennig Q on 23/2/2023.
//

import UIKit
import Alamofire
import HandyJSON
import SwiftyJSON

class DictionaryService: BaseService {
    //MARK: -获取panel list
    func getPanelModels(_ queryStr: String,installationDate: String){
        var urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetPanelModelListAPI + queryStr.trimmingCharacters(in: .whitespaces))
        if installationDate != "" {
            urlString += "&date=" + installationDate
        }
        urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            self.returnBlock(obj, nil)
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -获取inverter list
    func getInverterModels(_ queryStr: String,installationDate: String){
        var urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetInverterModelListAPI + queryStr.trimmingCharacters(in: .whitespaces))
        if installationDate != "" {
            urlString += "&date=" + installationDate
        }
        urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            self.returnBlock(obj, nil)
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -获取inverter list
    func getBatteryModels(_ queryStr: String,installationDate: String){
        var urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetBatteryModelListAPI + queryStr.trimmingCharacters(in: .whitespaces))
        if installationDate != "" {
            urlString += "&date=" + installationDate
        }
        urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            self.returnBlock(obj, nil)
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -获取tank list
    func getTankModels(_ queryStr: String,installationDate: String){
        var urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetTankModelListAPI + queryStr.trimmingCharacters(in: .whitespaces))
        if installationDate != "" {
            urlString += "&date=" + installationDate
        }
        urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            self.returnBlock(obj, nil)
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -本地数据库获取state list
    func getStateList(_ closure: @escaping ([AddressModel])->Void){
        
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.StateListAPI), method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: {(obj, _) -> Void in
            if let array = obj as? NSArray{
                if let data = try? JSONSerialization.data(withJSONObject: array, options: []){
                    do{
                        let list = try JSONDecoder().decode([AddressModel].self, from: data)
                        closure(list)
                    }catch{
                        DebugLog("State list从网络获取转换为[AddressModel]失败")
                    }
                }
            }
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -本地数据库获取Suburb list
    func getSuburbList(_ lastTime: String, _ closure: @escaping ([AddressModel])->Void){
            let urlStr = APIConfig.getRequestAPIForV2(APIConfig.SuburbListAPI) + "?last_time=" + lastTime
            let alRequest = ALRequest.init(mainURL: urlStr, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: {(obj, _) -> Void in
                
                if let array = obj as? NSArray{
                    if let data = try? JSONSerialization.data(withJSONObject: array, options: []){
                        do{
                            let list = try JSONDecoder().decode([AddressModel].self, from: data)
                            closure(list)
                        }catch{
                            DebugLog("Suburb list从网络获取转换为[AddressModel]失败")
                        }
                    }
                }
                
            }) {(code, obj) -> Void in
                self.errorBlock?(code, obj)
            }
            alRequest.startRequest()
        
        
    }
    //MARK: -本地数据库获取Street type list
    func getStreetTypeList(_ lastTime: String, _ closure: @escaping ([AddressModel])->Void){
        
        let urlStr = APIConfig.getRequestAPIForV2(APIConfig.StreetTypeListAPI) + "?last_time=" + lastTime
        let alRequest = ALRequest.init(mainURL: urlStr, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: {(obj, _) -> Void in
            
            if let array = obj as? NSArray{
                if let data = try? JSONSerialization.data(withJSONObject: array, options: []){
                    do{
                        let list = try JSONDecoder().decode([AddressModel].self, from: data)
                        closure(list)
                    }catch{
                        DebugLog("Street Type list从网络获取转换为[AddressModel]失败")
                    }
                }
            }
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -本地数据库获取Unit type list
    func getUnitTypeList(_ lastTime: String, _ closure: @escaping ([AddressModel])->Void){
        
        let urlStr = APIConfig.getRequestAPIForV2(APIConfig.UnitTypeListAPI) + "?last_time=" + lastTime
        let alRequest = ALRequest.init(mainURL: urlStr, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: {(obj, _) -> Void in
            
            if let array = obj as? NSArray{
                if let data = try? JSONSerialization.data(withJSONObject: array, options: []){
                    do{
                        let list = try JSONDecoder().decode([AddressModel].self, from: data)
                        closure(list)
                    }catch{
                        DebugLog("Unit Type list从网络获取转换为[AddressModel]失败")
                    }
                }
            }
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: - 根据输入的地址字符串拆分地址state,suburb, street ,unit ,post code 等信息
    func getAddressList(_ addressStr: String){
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.GetAddressListAPI)
        let params: Parameters = [ "full_address" : addressStr]
        let alRequest = ALRequest.init(mainURL: url, method: .get, headers: RequestConstant.AuthLoginOtherParam, paramDict: params, successBlock: { (obj, _ ) -> Void in
            guard let result = obj else {return}
            let json = JSON(result)
            if let list = JSONDeserializer<PhysicalAddressViewModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<PhysicalAddressViewModel>{
                self.returnBlock(list, nil)
            }
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -获取installer list
    func getInstallerList(companyId: Int, queryStr: String = ""){
        var urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetInstallerListAPI) + "?company_id=\(companyId)"
        if queryStr != ""{
            urlString += "&q=" + queryStr
        }
        
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            guard let data = obj else{
                return
            }
            //data list
            let json = JSON(data)
            if let list = JSONDeserializer<MyInformationModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<MyInformationModel>{
                self.returnBlock(list, nil)
            }
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -获取designer list
    func getDesignerList(companyId: Int, queryStr: String = ""){
        var urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetDesignerListAPI) + "?company_id=\(companyId)"
        if queryStr != ""{
            urlString += "&q=" + queryStr
        }
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            guard let data = obj else{
                return
            }
            //data list
            let json = JSON(data)
            if let list = JSONDeserializer<MyInformationModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<MyInformationModel>{
                self.returnBlock(list, nil)
            }
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -获取electricial list
    func getElectricianList(companyId: Int, queryStr: String = ""){
        var urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetElectricialListAPI) + "?company_id=\(companyId)"
        if queryStr != ""{
            urlString += "&q=" + queryStr
        }
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            guard let data = obj else{
                return
            }
            //data list
            let json = JSON(data)
            if let list = JSONDeserializer<MyInformationModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<MyInformationModel>{
                self.returnBlock(list, nil)
            }
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    func getWeather(latitude: String, longitude: String){
        let urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetWeatherAPI) + "?latitude=\(latitude)&longitude=\(longitude)"
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            guard let data = obj else{
                self.returnBlock(nil, nil)
                return
            }
            //data list
            let json = JSON(data)
            if let list = JSONDeserializer<DayWeatherModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<DayWeatherModel>{
                self.returnBlock(list, nil)
            }
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: - 创建job时，获取osw或other的warehouse
    func getDeliveryList(deliveryWarehouseType: DeliveryWarehouseType, companyID: Int ){
        let urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetDeliveryListAPI) + "?company_id=\(companyID)"
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
           
            if let dic = obj as? NSDictionary {
                if let data = dic.object(forKey: deliveryWarehouseType.rawValue.lowercased()) {
                    let json = JSON(data)
                    if let list = JSONDeserializer<DeliveryWarehouseModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<DeliveryWarehouseModel>{
                        self.returnBlock(list, nil)
                    }
                }
            }
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: - other增加delivery warehouse
    func createDeliveryWarehouse(addressModel: PhysicalAddressViewModel, companyID: Int ){
        let params: Parameters = ["company_id": companyID ,
                                  "address_text": addressModel.final_full_address,
                                  "unit_type": addressModel.unit_type,
                                  "unit_number": addressModel.unit_number,
                                  "street_number": addressModel.street_number,
                                  "street_name": addressModel.street_name,
                                  "street_type": addressModel.street_type,
                                  "suburb": addressModel.suburb,
                                  "state": addressModel.state,
                                  "post_code": addressModel.post_code,
                                  "latitude": addressModel.latitude,
                                  "longitude": addressModel.longitude
        ]
        
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.CreateDeliveryAPI), method: .post, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: {(obj, _) -> Void in
            if let dic = obj as? NSDictionary {
                if let data = dic.object(forKey: DeliveryWarehouseType.other.rawValue.lowercased()) {
                    let json = JSON(data)
                    if let list = JSONDeserializer<DeliveryWarehouseModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<DeliveryWarehouseModel>{
                        self.returnBlock(list, nil)
                    }
                }
            }
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
}
